import React from 'react';
import { Table,message } from 'antd';
import './Batch.css'
import * as api from '../../../utils/api'
import axios from '../../../utils/http'
import ExportJsonExcel from 'js-export-excel'

class Batch extends React.Component {
    constructor(){
        super()
        this.state={
            columns: [
                {
                  title: 'ID',
                  dataIndex: 'orderId',
                  align:'center',
                },
                {
                  title: '订单号',
                  dataIndex: 'orderCode',
                  align:'center',
                },
                {
                  title: '收货人',
                  dataIndex: 'harvestPeople',
                  align:'center',
                  render:(text,record,index)=>{
                      return(
                          <div>
                              {record.memLocations.memName}
                          </div>
                      )
                  }
                },
                {
                  title: '手机',
                  dataIndex: 'telephone',
                  align:'center',
                  render:(text,record,index)=>{
                    return(
                        <div>
                            {record.memLocations.memNum}
                        </div>
                    )
                }
                },
                {
                  title: '配送方式',
                  dataIndex: 'sendMethod',
                  render:(text,record,index)=>{
                      return(
                          <div>
                              {
                                  index === 0 ? <div><select name="" id="" onChange={(e)=>this.getCourier(record,e)} value={record.sendMethodVal}>
                                                        <option value="请选择">请选择</option>
                                                        <option value="中通快递">中通快递</option>
                                                        <option value="申通快递">申通快递</option>
                                                        <option value="圆通快递">圆通快递</option>
                                                        <option value="韵达快递">韵达快递</option>
                                                        <option value="顺丰快递">顺丰快递</option>
                                                        <option value="菜鸟裹裹">菜鸟裹裹</option>
                                                    </select>
                                                    <button type="button" className="copyBtn" onClick={this.getAllSelect}>同步以下</button>
                                                </div>
                                             : <div>
                                                    <select name="" id="" onChange={(e)=>this.getOtherCourier(record,e)} value={record.sendMethodVal}>
                                                        <option value="请选择">请选择</option>
                                                        <option value="中通快递">中通快递</option>
                                                        <option value="申通快递">申通快递</option>
                                                        <option value="圆通快递">圆通快递</option>
                                                        <option value="韵达快递">韵达快递</option>
                                                        <option value="顺丰快递">顺丰快递</option>
                                                        <option value="菜鸟裹裹">菜鸟裹裹</option>
                                                    </select>
                                               </div>
                              }
                              
                          </div>
                      )
                  }
                },
                {
                    title: '快递单号',
                    dataIndex: 'kuaiDiDanHao',
                    align:'center',
                    render:(text,record,index)=>{
                        return(
                            <div>
                                <input type="text" onChange={(e)=>this.changeCurKuaiDiDanHao(record,e)}/>
                            </div>
                        )
                    }
                },
            ],
            data:[
                /* {
                    bulkId: null,
                    comspec: null,
                    costinfor: null,
                    costinforId: null,
                    goods: null,
                    goodsId: null,
                    memLocationid: null,
                    memLocations: {memLocationid: null, memName: "", memNum: "", memLocation: null, memStatus: null},
                    member: null,
                    memberId: null,
                    orderBu: null,
                    orderClass: null,
                    orderCm: null,
                    orderCode: "",
                    orderDm: "",
                    orderDt: null,
                    orderId: null,
                    orderIn: "",
                    orderOt: null,
                    orderPm: null,
                    orderPt: null,
                    orderStatu: null,
                    orderStatus: null,
                    ordoper: null,
                } */
            ],
            curPage:1,
            curPageSize:3,
            curPageData:[],
            sendMethodVal:'',
            selectedArr:[],
        }
    }
    componentDidMount(){
        // 向后台请求订单列表的数据 === 注意这里请求的数据都是订单为待发货的订单数据
        axios({
            method:'GET',
            url:api.GET_QUERYBULKDELIVERY,
        }).then(data=>{
            console.log(data.data.data)
            let dataArr = data.data.data
            dataArr = dataArr.map((item,i)=>{
                item.key = i+1
                item.isSuccessFlag = false
                return item
            })
            let start = 0
            let end = start + this.state.curPageSize
            let curPageData = dataArr.slice(start,end)
            if(dataArr.length>0){
                this.setState({
                    data:dataArr,
                    curPageData
                })
            }
        })
        /* let start = 0
        let end = start + this.state.curPageSize
        let curPageData = this.state.data.slice(start,end)
        this.setState({
            curPageData
        }) */
    }
     // 页码改变的时候   
    pageNumChange = (page,pageSize)=>{
        let start = (page-1)*this.state.curPageSize
        let end = start + this.state.curPageSize
        let curPageData = this.state.data.slice(start,end)
        this.setState({
            curPage:page,
            curPageData,
        })
    }
    //跳到首页
    toPageStart = ()=>{
    this.setState({
        curPage:1,
    })
    }   
    // 跳转到尾页
    toPageEnd = ()=>{
    let totalPage = Math.ceil(this.state.data.length/this.state.curPageSize)
    this.setState({
        curPage:totalPage,
     })
    }
    // 第一行的快递公司
    getCourier=(curRow,e)=>{
        let data = [...this.state.data]
        data.forEach(item=>{
            if(item.orderId === curRow.orderId){
                item.orderDm = e.target.value
            }
        })
        let start = (this.state.curPage-1)*this.state.curPageSize
        let end = start + this.state.curPageSize
        let curPageData = data.slice(start,end)

        this.setState({
            data,
            curPageData
        })
        


        /* let data = [...this.state.data]
        data.forEach(item=>{
            if(item.orderId === curRow.orderId){
                item.sendMethodVal = e.target.value
            }
        })
        let start = (this.state.curPage-1)*this.state.curPageSize
        let end = start + this.state.curPageSize
        let curPageData = data.slice(start,end)

        this.setState({
            data,
            curPageData
        }) */

    }
    // 同步当前页的所有快递公司
    getAllSelect=()=>{
        let data = [...this.state.data]
        let curPageDataArr = [...this.state.curPageData]
        let val = curPageDataArr[0].orderDm
        curPageDataArr.forEach(item=>{
            item.orderDm = val
        })

        for(let i=0; i<data.length; i++){
            for(let j=0; j<curPageDataArr.length; j++){
                if(data[i].orderId===curPageDataArr[j].orderId){
                    data[i].orderDm = val
                }
            }
        }
        this.setState({
            data:data,
            curPageData:curPageDataArr
        })
    }
    getOtherCourier=(curRow,e)=>{
        // 除了第一行的其他快递公司
        let data = [...this.state.data]
        data.forEach(item=>{
            if(item.orderId === curRow.orderId){
                item.orderDm = e.target.value
            }
        })
        this.setState({
            data
        })
    }
    // 批量发货
    piLiangFaHuo=()=>{
        let curPageData = [...this.state.curPageData]
        // console.log(curPageData)
        curPageData.forEach(item=>{
            if(item.orderIn!=='' && item.orderDm!=='请选择'){
                item.isSuccessFlag = true
            }else{
                item.isSuccessFlag = false
            }
        })
        console.log(curPageData)
        let myArr = curPageData.filter(item=>{
            return item.isSuccessFlag === true
        })

        console.log(myArr)
        if(myArr.length>0){
            curPageData.forEach(item=>{
                item.orderStatu = 3
            })
            
            console.log(curPageData)
            axios({
                method:'POST',
                url:api.POST_UPDATEBULKDELIVERYSTATUS,
                data:curPageData
            }).then(data=>{
                // 刷新页面
                if(data.data.code === 200){
                    message.success('批量发货成功！')
                    window.location.reload()
                }
            })
        }else{
            message.warning('请完善当前页的发货信息！！！')
        }
    }
    // 修改当前快递单号
    changeCurKuaiDiDanHao=(curRow,e)=>{
        let data = [...this.state.data]
        data.forEach(item=>{
            if(item.orderId === curRow.orderId){
                item.orderIn = e.target.value
            }
        })
        this.setState({
            data
        })
    }
    // 选中项
    onSelectChange=(selectRowKeys,selectRowArr)=>{
        // console.log(selectRowKeys)
        // console.log(selectRow)
        this.setState({
            selectedArr:selectRowArr
        })
    }
    // 导出订单
    downloadExcel = () => {
        // console.log(this.state.selectedArr)
        let dataArr = [...this.state.selectedArr]
        let data = dataArr.length>0 ? dataArr : '';//表格数据
        var option={};
        let dataTable = [];
        if (data) {
          for (let i in data) {
            if(data){
              let obj = {
                '订单ID': data[i].orderId,
                '商品名称': data[i].goods.goodsName,
                '订单号': data[i].orderCode,
                '下单时间': new Date(data[i].orderOt).toLocaleString().replace(/\//g,'-').replace(/[\u4e00-\u9fa5]/g,""),
                '收货人': data[i].memLocations.memName,
                '收获人手机号': data[i].memLocations.memNum,
                '收获地址': data[i].memLocations.memLocation,
                '商品总金额': data[i].costinfor.costinforTaog,
              }
              dataTable.push(obj);
            }
          }
        }
        option.fileName = '订单信息列表'
        option.datas=[
          {
            sheetData:dataTable,
            sheetName:'订单信息列表',
            sheetFilter:['订单ID','商品名称','订单号','下单时间','收货人','收获人手机号','收获地址','商品总金额'],
            sheetHeader:['订单ID','商品名称','订单号','下单时间','收货人','收获人手机号','收获地址','商品总金额'],
          }
        ];
       
        var toExcel = new ExportJsonExcel(option); 
        toExcel.saveExcel();        
    }
    render(){
        return(
            <div className="batchBoxClass">
                <h1>批量操作</h1>
                <Table rowSelection={{onChange:this.onSelectChange}} rowKey={(record)=>record.orderId} columns={this.state.columns} dataSource={this.state.data} pagination={
                    {
                        total:this.state.data.length,
                        defaultCurrent:this.state.curPage,
                        defaultPageSize:this.state.curPageSize,
                        current:this.state.curPage,
                        pageSize:this.state.curPageSize,
                        showTotal:(total) => (`共${Math.ceil(this.state.data.length/this.state.curPageSize)}页${total}条记录`),
                        onChange:this.pageNumChange,
                    }
                }/>
                <div className="pagenationbox clearFloat">
                    <div className='allAndChu'>
                        <span className="checkBtn" onClick={this.piLiangFaHuo}>批量发货</span>
                        <span className="deleteBtn" onClick={this.downloadExcel}>导出订单</span>
                    </div>
                    <div>
                        <div className="pageBtnBox">
                                <span className="checkBtn" onClick={this.toPageStart}>首页</span>
                                <span className="checkBtn" onClick={this.toPageEnd}>尾页</span>
                        </div>
                    </div>
                    {/* <div className='pageNation'>
                        <div className='clearFloat'>
                            <div className='floatLeft'>
                                <Pagination
                                    className='purpleTxt'
                                    total={this.state.data.length}
                                    defaultCurrent={this.state.curPage}
                                    defaultPageSize={this.state.curPageSize}
                                    current={this.state.curPage}
                                    pageSize={this.state.curPageSize}
                                    showTotal={total => `共${Math.ceil(this.state.data.length/this.state.curPageSize)}页${total}条记录`}
                                    onChange={this.pageNumChange}
                                />
                            </div>
                            <div className="pageBtnBox">
                                <span className="checkBtn" onClick={this.toPageStart}>首页</span>
                                <span className="checkBtn" onClick={this.toPageEnd}>尾页</span>
                            </div>
                        </div>
                    </div> */}
                </div>
                <p>备注：批量发货操作只限于当前页</p>
            </div>
        )
    }
}
export default Batch;